<template>
	<view>

		<view class="wechat_login">
			<view class="img">
				<image src="@/static/images/wechat_login.png" mode="widthFix"></image>
			</view>
			<view class="btn-wrapper">
				<button v-if="!isCheck" class="item grant" type="primary"  lang="zh_CN" @click="getShoiquan">去授权</button>

				<button v-else class="bg-green btn1" type="primary" open-type="getPhoneNumber" lang="zh_CN" @getphonenumber="getphonenumber">授权手机号</button>
			</view>
		</view>
		<view class="row-center" style="margin: 15px;">
			<image @click="tonfyi" v-if="!isCheck" src="../../static/images/weixuanzhong.png" class="w-32 h-32" >
			<image  @click="tonfyi"  v-else src="../../static/images/xuanzhong.png" class="w-32 h-32" >
			<text>同意</text>
			<text style="color: #007AFF;" @click="goService">《用户服务协议》、</text><text style="color: #007AFF;" @click="goPrivacy">《隐私政策》</text>
		</view>
	
	</view>
</template>

<script>
	const app = getApp();
	let statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
	import {

		getUserPhone,
	} from '@/api/api.js';
	import {
		LOGO_URL,
		EXPIRES_TIME,
		USER_INFO,
		STATE_R_KEY
	} from '@/config/cache';
	import {
		getUserInfo
	} from '@/api/user.js';
	export default {
		data() {
			return {
				isUp: false,
				phone: '',
				statusBarHeight: statusBarHeight,
				isHome: false,
				isPhoneBox: false,
				code: '',
				authKey: '',
				options: '',
				userInfo: {},
				codeNum: 0,
				codeVal: "",
				isClick: false,
				isCheck: false,
			};
		},
		components: {
		},
		onLoad(options) {
	
			let that = this;
		
		},
		onReady(){
			let that = this
			// #ifdef MP
			wx.login({
			  success (res) {
			    if (res.code) {
			     that.codeVal = res.code
			    } else {
			      console.log('登录失败！' + res.errMsg)
			    }
			  }
			})
			// #endif
		},
		
		methods: {
			getShoiquan(){
				return this.$util.Tips({
					title: "请同意协议"
				})
			},
			tonfyi(){
				
				this.$set(this,"isCheck" ,!this.isCheck)
			},
			goService(){
				uni.navigateTo({
					url:"/pages/web/web?url=https://zb.gyqsbs.cn/yszc.html"
				})
			},
			goPrivacy(){
				uni.navigateTo({
					url:"/pages/web/web?url=https://zb.gyqsbs.cn/yszc.html"
				})
			},
			back() {
				uni.navigateBack();
			},
			home() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			// 弹窗关闭
			maskClose() {
				this.isUp = false;
			},
			bindPhoneClose(data) {
				if (data.isStatus) {
					this.isPhoneBox = false;
					this.$util.Tips({
						title: '登录成功',
						icon: 'success'
					}, {
						tab: 3
					});
				} else {
					this.isPhoneBox = false;
				}
			},
			// #ifdef MP
			// 小程序获取手机号码
			getphonenumber(e) {
				console.log(111,e)
				if(!this.isCheck){
					return this.$util.Tips({
						title: "请同意协议"
					})
				}
				// if(this.isClick){
				// 	return this.$u.toast("请勿重复点击！")
				// }
				uni.showLoading({
					title: '正在登录中'
				});
				this.isClick= true
				this.getUserPhoneNumber(e.detail.encryptedData, e.detail.iv,  e.detail.code);
				// Routine.getCode()
				// 	.then(code => {
				// 		this.getUserPhoneNumber(e.detail.encryptedData, e.detail.iv, code);
				// 	})
				// 	.catch(error => {
				// 		this.$util.Tips({
				// 			title: '请重新授权',
				// 		});
				// 		uni.hideLoading();
				// 	});
			},
			// 小程序获取手机号码回调
			getUserPhoneNumber(encryptedData, iv, code) {
				getUserPhone({
						encryptedData: encryptedData,
						iv: iv,
						code: code,
						opcode: this.codeVal
					})
					.then(res => {
						this.isClick= true
						console.log(123,res)
						this.$store.commit('LOGIN', {
							token: res.token,
						}); 
						var userInfo = res.user;
						this.$store.commit('SETUID', userInfo.id);
						this.$store.commit('UPDATE_USERINFO', userInfo);
						// this.$util.Tips({
						// 	title: '登录成功',
						// 	icon: 'success'
						// }, {
						// 	tab: 3
						// });
						uni.reLaunch({
							url:'/pages/index/index'
						})
					})
					.catch(res => {
						this.isClick= true
						this.$util.Tips({
							title: '请重新授权',
						});
						uni.hideLoading();
					});
			},
			/**
			 * 获取个人用户信息
			 */
			getUserInfo: function() {
				let that = this;
				getUserInfo().then(res => {
					uni.hideLoading();
					that.userInfo = res.data;
					that.$store.commit('SETUID', res.data.uid);
					that.$store.commit('UPDATE_USERINFO', res.data);
					that.$util.Tips({
						title: '登录成功',
						icon: 'success'
					}, {
						tab: 3
					});
				});
			},
			setUserInfo(e) {
				uni.showLoading({
					title: '正在登录中'
				});
				Routine.getCode()
					.then(code => {
						this.getWxUser(code);
					})
					.catch(res => {
						uni.hideLoading();
					});
			},
			//小程序授权api替换 getUserInfo
			getUserProfile() {
				uni.showLoading({
					title: '正在登录中'
				});
				let self = this;
				Routine.getUserProfile()
					.then(res => {
						Routine.getCode()
							.then(code => {
								let userInfo = res.userInfo;
								userInfo.code = code;
								userInfo.spread_spid = app.globalData.spid; //获取推广人ID
								userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID
								Routine.authUserInfo(userInfo)
									.then(res => {
										if (res.data.key !== undefined && res.data.key) {
											uni.hideLoading();
											self.authKey = res.data.key;
											self.isPhoneBox = true;
										} else {
											uni.hideLoading();
											let time = res.data.expires_time - self.$Cache.time();
											self.$store.commit('LOGIN', {
												token: res.data.token,
												time: time
											});
											this.getUserInfo()
										}
									})
									.catch(res => {
										uni.hideLoading();
										uni.showToast({
											title: res.msg,
											icon: 'none',
											duration: 2000
										});
									});
							})
							.catch(res => {
								uni.hideLoading();
							});
					})
					.catch(res => {
						uni.hideLoading();
					});
			},
			getWxUser(code) {
				let self = this;
				Routine.getUserInfo()
					.then(res => {
						let userInfo = res.userInfo;
						userInfo.code = code;
						userInfo.spread_spid = app.globalData.spid; //获取推广人ID
						userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID
						Routine.authUserInfo(userInfo)
							.then(res => {
								if (res.data.key !== undefined && res.data.key) {
									uni.hideLoading();
									self.authKey = res.data.key;
									self.isPhoneBox = true;
								} else {
									uni.hideLoading();
									let time = res.data.expires_time - self.$Cache.time();
									self.$store.commit('LOGIN', {
										token: res.data.token,
										time: time
									});
									self.$util.Tips({
										title: res.msg,
										icon: 'success'
									}, {
										tab: 3
									});
								}
							})
							.catch(res => {
								uni.hideLoading();
								uni.showToast({
									title: res,
									icon: 'none',
									duration: 2000
								});
							});
					})
					.catch(res => {
						uni.hideLoading();
					});
			},

			// #endif
			// #ifdef H5
			// 获取url后面的参数
			getQueryString(name) {
				var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
				var reg_rewrite = new RegExp('(^|/)' + name + '/([^/]*)(/|$)', 'i');
				var r = window.location.search.substr(1).match(reg);
				var q = window.location.pathname.substr(1).match(reg_rewrite);
				if (r != null) {
					return unescape(r[2]);
				} else if (q != null) {
					return unescape(q[2]);
				} else {
					return null;
				}
			},
			// 公众号登录
			wechatLogin() {
				if (!this.code || this.options.scope !== 'snsapi_base') {
					this.$wechat.oAuth('snsapi_userinfo', '/pages/users/wechat_login/index');
				} else {
					if (this.authKey) {
						this.isUp = true;
					}
				}
			},
			// 输入手机号后的回调
			wechatPhone() {
				this.$Cache.clear('snsapiKey');
				if (this.options.back_url) {
					let url = uni.getStorageSync('snRouter');
					url = url.indexOf('/pages/index/index') != -1 ? '/' : url;
					if (url.indexOf('/pages/users/wechat_login/index') !== -1) {
						url = '/';
					}
					if (!url) {
						url = '/pages/index/index';
					}
					let self = this;
					this.isUp = false;
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					});
					setTimeout(res => {
						location.href = url;
					}, 800);
				} else {
					uni.navigateBack();
				}
			}
			// #endif
		}
	};
</script>

<style lang="scss">
	page {
		background: #fff;
	}

	.wechat_login {
		padding: 72rpx 34rpx;

		.img image {
			width: 100%;
		}

		.btn-wrapper {
			margin-top: 86rpx;
			padding: 0 66rpx;

			button {
				width: 100%;
				height: 86rpx;
				line-height: 86rpx;
				margin-bottom: 40rpx;
				border-radius: 120rpx;
				font-size: 30rpx;

				&.btn1 {
					color: #fff;
				}

				&.btn2 {
					color: #007AFF;
					border: 1px solid #007AFF;
				}
			}
		}
	}

	.title-bar {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
	}

	.icon {
		position: absolute;
		left: 30rpx;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 86rpx;
		height: 86rpx;

		image {
			width: 50rpx;
			height: 50rpx;
		}
	}
</style>
